import React, {Component} from 'react';
import {Card, Form, Input, Button, Image, DatePicker, message, Modal,} from 'antd';
import {
  ArrowLeftOutlined, ExclamationCircleOutlined,
  LeftOutlined,
} from '@ant-design/icons';
import './info_detail.less';
import {reqBookInfosDetail} from '../../../../api/book';
import moment from 'moment';
import Editor from '../../../books/detail/infos/editor';
import {reqUpdateBookInfo, reqDeleteBookInfo} from '../../../../api/book';

// 首页
export default class BookInfoDetail extends Component {
  state = {
    result: {},
  }
  // 点击返回
  backClick = () => {
    this.props.history.goBack();
  }
  // 发起删除请求
  deleteBookInfo = async () => {
    try {
      await reqDeleteBookInfo({items: [this.state.result._id]});
      message.success('删除成功');
      // 需要清此页面缓存
      this.props.history.replace('/admin/books/infos');
    } catch (e) {
      console.log(e);
      message.error(e.data.message);
    }
  }
  // 点击modal 的删除按钮
  handleDelOk = () => {
    this.deleteBookInfo();
  }
  // 删除
  deleteClick = () => {
    Modal.confirm({
      title: '删除标签',
      icon: <ExclamationCircleOutlined/>,
      content: '请注意，你将永久删除该条资讯！',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleDelOk(),
    });
  }
  // 获取图书资讯数据
  getBookInfo = async () => {
    try {
      const id = this.props.match.params.id;
      const {data:result} = await reqBookInfosDetail(id, {fields: 'note_content'});
      this.setState({result})
    } catch (e) {
      console.log(e);
      message.error(e.data.name || e.data.message);
    }
  }
  // 更新图书资讯数据
  updateBookInfo = async (data) => {
    try {
      const id = this.props.match.params.id;
      const {data: res} = await reqUpdateBookInfo(id, data);
      message.success(res.message);
      this.props.history.replace('/admin/books/infos');
    } catch (e) {
      console.log(e);
      message.success(e.data.name || e.data.message);
    }
  }
  componentDidMount() {
    this.getBookInfo();
  }
  saveClick = () => {
    this.formRef.validateFields().then(values => {
      const pub_date = moment(values.pub_date._d).format('YYYY-MM-DD HH:mm:ss');
      const vals = Object.assign(values,{pub_date});
      this.updateBookInfo(vals);
    }).catch(e => {
      message.error(e.data.name || e.data.message);
    })
  }

  render() {
    const {result} = this.state;
    const title = (
      <div className='card-header'>
        <div className='card-header-left' onClick={this.backClick}>
          <ArrowLeftOutlined/>
          <div className='back'>返回</div>
        </div>
        <div className='card-header-right'>
          修改 资讯详情
        </div>
      </div>
    );
    const formItemLayout = {
      labelAlign: 'left',
      labelCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 4
        }
      },
      wrapperCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 8,
        },
      },
    };

    return (
      <Card title={title}>
        {
          Object.keys(result).length > 0 &&
          <Form
            size='middle'
            {...formItemLayout}
            ref={(instance) => this.formRef = instance}
            initialValues={Object.assign(result, {pub_date: moment(result.pub_date, 'YYYY/MM/DD HH:mm')})}
          >
            <Form.Item
              label="标题"
              name="title"
              rules={[
                {
                  required: true,
                  message: '请输入标题',
                },
              ]}
            >
              <Input/>
            </Form.Item>

            <Form.Item
              label="作者"
              name="author"
              rules={[
                {
                  required: true,
                  message: '请输入作者',
                },
              ]}
            >
              <Input/>
            </Form.Item>
            <Form.Item
              label="作者头像"
              name="author_avatar"
            >
              <Image
                width={50}
                height={50}
                src={result.author_avatar}
              />
            </Form.Item>
            <Form.Item label='封面图' name='note_image'>
              <Image width={100} src={result.note_image} />
            </Form.Item>
            <Form.Item
              label="内容"
              name="note_content"
              trigger='onBlur'
              validateTrigger='onBlur'
              rules={[
                {
                  required: true,
                },
                {
                  validateTrigger: 'onBlur',
                  validator: (rule, value) => {
                    if (typeof value === 'object' && value.toHTML() === '<p></p>') {
                      return Promise.reject('请输入正文内容')
                    } else {
                      return Promise.resolve()
                    }
                  }
                }
              ]}
              wrapperCol={{
                xs:{span: 24}, sm: {span: 24}
              }}
            >
              {/*自定义表单组件*/}
              {/*验证必须同时有onBlur，否则validator不会生效*/}
              <Editor />
            </Form.Item>
            <Form.Item label='发布日期'
                       name='pub_date'
                       rules={[
                         {
                           required: true,
                           message: '请选择日期',
                         },
                       ]}
            >
              <DatePicker format={'YYYY/MM/DD HH:mm'} showTime showNow/>
            </Form.Item>
            <Form.Item
              wrapperCol={{
                xs:{span: 24}, sm: {span: 24}
              }}
            >
              <div className='form-footer'>
                <div className='form-footer-left'>
                  <Button onClick={this.backClick} size='large' icon={<LeftOutlined />}>
                    返回
                  </Button>
                  <Button type="primary"
                          className='delete-click'
                          danger
                          onClick={this.deleteClick}
                          size='large'
                  >
                    删除
                  </Button>
                </div>
                <div className='form-footer-right'>
                  <Button type="primary" onClick={this.saveClick} size='large'>
                    保存
                  </Button>
                </div>
              </div>
            </Form.Item>
          </Form>
        }
      </Card>
    )
  }
}


